<?php

namespace App\Http\Middleware;

use App\Http\Controllers\WechatController;
use App\Models\Student;
use App\User;
use Closure;
use Illuminate\Support\Facades\Auth;
use Log;

class CacheStudent
{
    /**
     * 如果是微信，如果注册了学生信息，直接写入session，如果没有，跳转到学生注册页
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //TODO delete
        if (!isWechat()) {
            $u = Student::where('openid', 'oHwEGs2nlJMpKJO7Id7-cIJOq7cY')->first();
            session(['openid' => 'oHwEGs2nlJMpKJO7Id7-cIJOq7cY']);
            session(['student' => $u]);
            return $next($request);
        }
        if (isWechat() && !$request->session()->exists('student')) {
            $openid = session('openid');
            if (empty($openid)) {
                $app = WechatController::app();
                try {
                    $user = $app->oauth->setRequest($request)->user();
                    $openid = $user->getId();
                    Log::info('Wechat User Login: openid' . $openid);
                    session(['openid' => $openid]);
                } catch (\Exception $exception) {
                    Log::info('获取微信信息。。。');

                    $response = $app->oauth->scopes(['snsapi_base'])
                        ->setRequest($request)
                        ->redirect($request->url());
                    return $response;
                }
            }
            $u = Student::where('openid', $openid)->first();
            //TODO 未判断是否过期
            if ($u) {
                session(['student' => $u]);
            } else {
                return redirect(url('student/create'));
            }
        }
        return $next($request);
    }
}
